<template>
  <div class="wechat-index-container">
    <div class="hero-section">
      <div class="hero-content">
        <h1>艾西迪西共享用电</h1>
        <div class="hero-buttons">
          
          <el-button type="success" size="large" @click="handleRecharge" style="margin-left: 20px;">
            <i class="el-icon-coin"></i>
            用户充值
          </el-button>
          <el-button type="warning" size="large" @click="showRefundDialog" style="margin-left: 20px;">
            <i class="el-icon-refresh"></i>
            申请退款
          </el-button>
        </div>
      </div>
    </div>

    <!-- 退款对话框 -->
    <el-dialog
      title="申请退款"
      :visible.sync="refundDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="refundForm" :rules="refundRules" ref="refundForm" label-width="120px">
        <el-form-item label="充值订单号" prop="outTradeNo">
          <el-input
            v-model="refundForm.outTradeNo"
            placeholder="请输入充值订单号"
            clearable
          ></el-input>
        </el-form-item>
        
        <el-form-item label="退款金额">
          <el-input
            v-model="refundForm.refundAmount"
            placeholder="退款金额（分）"
            disabled
            style="color: #409EFF; font-weight: bold;"
          >
            <template slot="append">分</template>
          </el-input>
          <div style="font-size: 12px; color: #909399; margin-top: 5px;">
            当前退款金额固定为1分
          </div>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="warning" @click="handleRefund" :loading="refundLoading">
          确认退款
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { createPayOrder, getJSSDKConfig, createRefund } from '@/api/wechat'

export default {
  name: 'WechatIndex',
  data() {
    return {
      isWxReady: false,
      // 退款相关
      refundDialogVisible: false,
      refundLoading: false,
      refundForm: {
        outTradeNo: '',
        refundAmount: 1
      },
      refundRules: {
        outTradeNo: [
          { required: true, message: '请输入充值订单号', trigger: 'blur' },
          { min: 1, max: 64, message: '订单号长度在1到64个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.initWechatJSSDK()
  },
  methods: {
    // 初始化微信JSSDK
    async initWechatJSSDK() {
      // 检查是否在微信环境中
      if (typeof wx === 'undefined') {
        console.log('当前不在微信环境中')
        return
      }

      try {
        // 获取当前页面URL
        const currentUrl = "https://7249koys0796.vicp.fun/#/wechat/index"
        
        // 获取JSSDK配置
        const response = await getJSSDKConfig(currentUrl)
        
        if (response.code === 200) {
          const config = response.data
          
          // 配置微信JSSDK
          wx.config({
            debug: false, // 生产环境设为false
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: ['chooseWXPay'] // 需要使用的JS接口列表
          })

          // 配置完成后
          wx.ready(() => {
            console.log('微信JSSDK配置成功')
            this.isWxReady = true
          })

          // 配置失败
          wx.error((res) => {
            console.error('微信JSSDK配置失败:', res)
            this.$message.error('微信环境初始化失败')
          })
        } else {
          console.error('获取JSSDK配置失败:', response.msg)
        }
      } catch (error) {
        console.error('初始化微信JSSDK失败:', error)
      }
    },
    goToLogin() {
      this.$router.push('/wechat/login')
    },
    async handleRecharge() {
      try {
        this.$message.info('正在创建支付订单...')
        
        const payRequest = {
          totalAmount: 1 // 支付金额为1分
        }
        
        const response = await createPayOrder(payRequest)
        
        if (response.code === 200) {
          this.$message.success('支付订单创建成功，正在调起微信支付...')
          
          // 调用微信支付
          const payParams = response.data
          console.log('支付参数:', payParams)
          
          // 检查是否在微信环境中
          if (typeof wx !== 'undefined' && this.isWxReady) {
            // 使用微信JSSDK的chooseWXPay方法
            // 注意：参数名必须与后端返回的字段名完全一致
            wx.chooseWXPay({
              appId: payParams.appId,
              timestamp: payParams.timeStamp, // 注意这里是timeStamp，不是timestamp
              nonceStr: payParams.nonceStr,
              package: payParams.package,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: (res) => {
                console.log('支付成功:', res)
                this.$message.success('支付成功！')
                this.handlePaymentSuccess()
              },
              fail: (res) => {
                console.log('支付失败:', res)
                if (res.errMsg && res.errMsg.includes('cancel')) {
                  this.$message.info('支付已取消')
                } else {
                  this.$message.error('支付失败，请重试')
                }
                this.handlePaymentFail(res)
              }
            })
          } else if (typeof wx !== 'undefined' && !this.isWxReady) {
            this.$message.warning('微信环境正在初始化，请稍后重试')
          } else {
            // 非微信环境，显示支付参数供调试
            this.$message.warning('当前不在微信环境中，无法调起支付')
            console.log('支付参数（非微信环境）:', payParams)
          }
        } else {
          this.$message.error(response.msg || '创建支付订单失败')
        }
      } catch (error) {
        console.error('充值失败:', error)
        this.$message.error('充值失败，请稍后重试')
      }
    },
    
    // 支付成功处理
    handlePaymentSuccess() {
      // 可以在这里添加支付成功后的逻辑
      // 比如：跳转到成功页面、刷新用户余额、显示成功提示等
      this.$message.success('充值成功！余额已更新')
      
      // 如果需要跳转到其他页面，可以使用：
      // this.$router.push('/success')
    },
    
    // 支付失败处理
    handlePaymentFail(error) {
      // 可以在这里添加支付失败后的逻辑
      // 比如：记录失败日志、显示重试按钮等
      console.error('支付失败详情:', error)
    },

    // 退款相关方法
    showRefundDialog() {
      this.refundDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refundForm.resetFields()
      })
    },

    async handleRefund() {
      this.$refs.refundForm.validate(async (valid) => {
        if (valid) {
          this.refundLoading = true
          try {
            this.$message.info('正在申请退款...')
            
            const response = await createRefund(this.refundForm)
            
            if (response.code === 200) {
              this.$message.success('退款申请成功！')
              this.refundDialogVisible = false
              // 重置表单
              this.$refs.refundForm.resetFields()
            } else {
              this.$message.error(response.msg || '退款申请失败')
            }
          } catch (error) {
            console.error('退款失败:', error)
            this.$message.error('退款失败，请稍后重试')
          } finally {
            this.refundLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wechat-index-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.hero-section {
  padding: 80px 40px;
  text-align: center;
  
  .hero-content {
    h1 {
      font-size: 48px;
      color: #2c3e50;
      margin: 0 0 20px 0;
      font-weight: 700;
    }
    
    p {
      font-size: 20px;
      color: #7f8c8d;
      margin: 0 0 40px 0;
      line-height: 1.6;
    }
    
    .hero-buttons {
      .el-button {
        padding: 15px 30px;
        font-size: 16px;
        
        i {
          margin-right: 8px;
        }
      }
    }
  }
}

.features-section {
  padding: 80px 40px;
  background: white;
  
  h2 {
    text-align: center;
    font-size: 36px;
    color: #2c3e50;
    margin: 0 0 60px 0;
    font-weight: 600;
  }
  
  .features-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 40px;
    max-width: 800px;
    margin: 0 auto;
    
    .feature-card {
      text-align: center;
      padding: 40px 30px;
      border-radius: 12px;
      background: #f8f9fa;
      
      .feature-icon {
        margin-bottom: 20px;
        
        i {
          font-size: 60px;
          color: #3498db;
        }
      }
      
      h3 {
        font-size: 24px;
        color: #2c3e50;
        margin: 0 0 15px 0;
        font-weight: 600;
      }
      
      p {
        color: #7f8c8d;
        line-height: 1.6;
        margin: 0;
      }
    }
  }
}

.cta-section {
  padding: 80px 40px;
  background: #f8f9fa;
  text-align: center;
  
  h2 {
    font-size: 36px;
    color: #2c3e50;
    margin: 0 0 20px 0;
    font-weight: 600;
  }
  
  p {
    font-size: 18px;
    color: #7f8c8d;
    margin: 0 0 40px 0;
    line-height: 1.6;
  }
  
  .el-button {
    padding: 15px 40px;
    font-size: 18px;
  }
}

// 退款对话框样式
.dialog-footer {
  text-align: right;
  
  .el-button {
    margin-left: 10px;
  }
}

// 退款表单样式
.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  .el-input-group__append {
    background-color: #f5f7fa;
    color: #606266;
    border-left: 1px solid #dcdfe6;
  }
}
</style>
